package builder

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"BuildAll/internal/platform"
	"BuildAll/internal/utils"

	"github.com/iwen-conf/colorprint/clr"
)

// BuildResults 构建结果
type BuildResults struct {
	Successful int
	Failed     int
	Skipped    int
	Duration   time.Duration
	Details    []BuildDetail
}

// BuildDetail 单个平台的构建详情
type BuildDetail struct {
	Platform   platform.Platform
	Success    bool
	Error      string
	OutputPath string
	Duration   time.Duration
}

// BuildAllPlatforms 构建所有平台
func BuildAllPlatforms(projectName, outputDir string, buildList []platform.Platform) BuildResults {
	// 记录成功和失败的构建
	var results BuildResults
	results.Details = make([]BuildDetail, 0, len(buildList))

	// 进度条宽度
	progressWidth := 50

	// 开始时间
	startTime := time.Now()

	// 构建所有组合
	for i, plat := range buildList {
		processed := i + 1
		utils.ShowProgress(processed, len(buildList), progressWidth)

		buildDetail := buildSinglePlatform(projectName, outputDir, plat)
		results.Details = append(results.Details, buildDetail)

		if buildDetail.Success {
			results.Successful++
		} else {
			results.Failed++
			// 换行以避免覆盖进度条
			fmt.Printf("\n%s %s/%s: %s\n",
				clr.FGColor("构建失败", clr.Red),
				clr.Bold(plat.OS),
				clr.Bold(plat.Arch),
				buildDetail.Error)
		}
	}

	// 完成后清空进度条行
	fmt.Printf("\r%s\r", strings.Repeat(" ", progressWidth+60))

	// 计算总用时
	results.Duration = time.Since(startTime)

	return results
}

// buildSinglePlatform 构建单个平台
func buildSinglePlatform(projectName, outputDir string, plat platform.Platform) BuildDetail {
	startTime := time.Now()
	detail := BuildDetail{
		Platform: plat,
	}

	// 构建输出文件名
	exeName := fmt.Sprintf("%s_%s_%s", projectName, plat.OS, plat.Arch)
	if plat.OS == "windows" {
		exeName += ".exe"
	}
	outputPath := filepath.Join(outputDir, exeName)
	detail.OutputPath = outputPath

	// 设置环境变量并执行go build
	cmd := exec.Command("go", "build", "-o", outputPath)
	cmd.Env = append(os.Environ(),
		fmt.Sprintf("GOOS=%s", plat.OS),
		fmt.Sprintf("GOARCH=%s", plat.Arch),
	)

	output, err := cmd.CombinedOutput()
	detail.Duration = time.Since(startTime)

	if err != nil {
		detail.Success = false
		detail.Error = fmt.Sprintf("%v\n%s", err, string(output))
	} else {
		detail.Success = true
	}

	return detail
}

// GetDetailedReport 获取详细的构建报告
func GetDetailedReport(results BuildResults) string {
	var report strings.Builder

	report.WriteString(clr.Bold("构建详细报告\n"))
	report.WriteString(fmt.Sprintf("%s: %s\n", clr.Bold("总用时"), clr.FGColor(results.Duration.String(), clr.Magenta)))
	report.WriteString(fmt.Sprintf("%s: %d, %s: %d, %s: %d\n\n",
		clr.Bold("成功"),
		results.Successful,
		clr.Bold("失败"),
		results.Failed,
		clr.Bold("跳过"),
		results.Skipped))

	report.WriteString(clr.Bold("成功的构建:\n"))
	for _, detail := range results.Details {
		if detail.Success {
			platform := fmt.Sprintf("%s/%s", detail.Platform.OS, detail.Platform.Arch)
			duration := utils.GetElapsedTime(time.Now().Add(-detail.Duration))

			report.WriteString(fmt.Sprintf("  %s: %s (%s)\n",
				clr.FGColor(platform, clr.Green),
				filepath.Base(detail.OutputPath),
				clr.FGColor(duration, clr.Cyan)))
		}
	}

	if results.Failed > 0 {
		report.WriteString("\n" + clr.Bold("失败的构建:\n"))
		for _, detail := range results.Details {
			if !detail.Success {
				platform := fmt.Sprintf("%s/%s", detail.Platform.OS, detail.Platform.Arch)
				report.WriteString(fmt.Sprintf("  %s: %s\n",
					clr.FGColor(platform, clr.Red),
					clr.FGColor(detail.Error, clr.Yellow)))
			}
		}
	}

	return report.String()
}
